require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.33.0/min/vs' }});

// 初始化编辑器并返回Promise
var editorPromise = new Promise((resolve, reject) => {
    require(['vs/editor/editor.main'], function() {
        var editor = monaco.editor.create(document.getElementById('editor'), {
            value: '',
            language: 'cpp',
            theme: 'vs-dark'
        });
        resolve(editor); // 将编辑器实例传递给 Promise
    });
});

// 确保在编辑器初始化后再执行提交代码的逻辑
document.getElementById('submit-btn').addEventListener('click', function() {
    editorPromise.then(editor => { // 使用 then 确保编辑器已初始化
        var code = editor.getValue(); // 获取编辑器的值
        
        const qobj = document.getElementById('qid');
        var problemId = qobj.textContent;
        // 显示模态窗口
        var modal = document.getElementById('myModal');
        modal.style.display = "block";
        var modalText = document.getElementById('modalText');
        var nextQuestionBtn = document.getElementById("next-question-btn");
        nextQuestionBtn.style.display = "none";
        modalText.innerText = '判题中...';
        modalText.classList.add('blink');

        // 延时发送请求
        setTimeout(function() {
            fetch('/judge', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ id: problemId, code: code })
            })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                modalText.classList.remove('blink'); // 移除闪烁类
                var result;
                var message=data.message;
                if(message.length==0)
                {
                    result="测试用例通过情况："+data.passed_status;
                    let parts = data.passed_status.split('/');
                    let leftNumber = parts[0];  
                    let rightNumber = parts[1];
                    if(leftNumber==rightNumber){
                        result+=" 恭喜你，通过全部测试用例！";
                        nextQuestionBtn.style.display = "block";
                    } else {
                        result+="\n还有测试用例没有通过哦，请再想想其他情况吧";
                    }
                }
                else
                {
                    console.log(result);
                    result="测试用例通过情况: ";
                    result+=data.passed_status;
                    result+="\nerr_message: ";
                    result+=message;
                }
                document.getElementById('modalText').innerText = result; // 假设后端返回的数据中有message字段
            })
            .catch((error) => {
                modalText.classList.remove('blink'); // 移除闪烁类
                console.error('Error:', error);
                alert('提交失败，请重试。');
            })
        }, 1000); // 延时1秒
    }).catch(error => {
        console.error('Editor initialization failed:', error);
        alert('编辑器初始化失败，请刷新页面重试。');
    });
});

// 显示模态框的函数
function showMessageBox(text) {
    var modal = document.getElementById('myModal');
    var modalText = document.getElementById('modalText');
    var nextQuestionBtn = document.getElementById("next-question-btn");
    modal.style.display = "block";
    modalText.innerText = text;
    modalText.classList.add('blink');
    nextQuestionBtn.style.display = "none";
}

// 关闭模态框的函数
function closeMessageBox() {
    var modal = document.getElementById('myModal');
    modal.style.display = "none";
}



// 挑战下一题按钮事件
document.getElementById("next-question-btn").addEventListener("click", function() {
    const qobj = document.getElementById('qid');
    const next = Number(qobj.textContent) + 1;
    window.location.href = "/question_page?qid=" + next.toString(); // 跳转到下一题
});

// 关闭模态框按钮事件
document.getElementById('closeModalBtn').addEventListener('click', function() {
    closeMessageBox();
});

// DOM加载完毕后执行
document.addEventListener('DOMContentLoaded', function() {
    Promise.all([editorPromise, fetchProblemData()])
    .then(results => {
        const editor = results[0];
        const data = results[1];
        editor.setValue(data.code);
    })
    .catch(error => {
        console.error('An error occurred:', error);
    });
});

// 获取题目数据
function fetchProblemData() {
    const params = getQueryParams();
    const qid = params['qid'];
    return fetch('/question_data_'+qid)
        .then(response => response.json())
        .then(data => {
            updatePageContent(data);
            return data;
        })
        .catch(error => {
            console.error('Error fetching problem data:', error);
        });
}

// 更新页面内容
function updatePageContent(data) {
    document.getElementById('qid').textContent = data.qid;
    document.getElementById('problem-name').textContent = data.qname;
    document.getElementById('difficulty').textContent = data.qlevel;
    document.getElementById('description').textContent = data.qdisc;
    document.getElementById('time-limit').textContent = data.t_limit;
    document.getElementById('memory-limit').textContent = data.s_limit;
    document.getElementById('hints').textContent = data.qcue;
}

// 获取URL参数
function getQueryParams() {
    const params = {};
    const queryString = window.location.search.substring(1);
    const vars = queryString.split('&');
    vars.forEach((pair) => {
        const [key, value] = pair.split('=');
        params[key] = decodeURIComponent(value);
    });
    return params;
}

// 提交记录按钮事件
var submitRecordBtn = document.getElementById('submit-record-btn');
var dataDropdown = document.getElementById('dataDropdown');
var dropdownContent = document.getElementById('dropdownContent');

submitRecordBtn.addEventListener('click', function() {
    const params = getQueryParams();
    const qid = params['qid'];
    dataDropdown.style.display = 'block';
    fetch('/submitrecord_'+qid)
        .then(response => response.json())
        .then(data => {
            dropdownContent.innerHTML = '';
            data.forEach(item => {
                const itemDiv = document.createElement('div');
                itemDiv.className = 'item-container';
                itemDiv.innerHTML = `<div class="status">${item.status}</div><div class="date">${item.date}</div>`;
                dropdownContent.appendChild(itemDiv);
            });
        })
        .catch(error => {
            console.error('Error:', error);
            dropdownContent.innerHTML = '请求失败，请重试。';
        });
});

// 关闭下拉页面的按钮事件
document.getElementById('closeDropdownBtn').addEventListener('click', function() {
    dataDropdown.style.display = 'none';
});